import utils from '../utils'
import Geom from '../geom'

function cleanShapes(shapes, arcs, type) {
  for (let i=0, n=shapes.length; i<n; i++) {
    shapes[i] = cleanShape(shapes[i], arcs, type)
  }
}
function cleanShape(shape, arcs, type) {
  return utils.editShapeParts(shape, (path) => {
    let cleaned = cleanPath(path, arcs)
    if (type == 'polygon' && cleaned) {
      removeSpikesInPath(cleaned) // assumed by addIntersectionCuts()
      if (Geom.getPlanarPathArea(cleaned, arcs) === 0) {
        cleaned = null
      }
    }
    return cleaned
  })
}
function cleanPath(path, arcs) {
  let nulls = 0
  for (let i=0, n=path.length; i<n; i++) {
    if (arcs.arcIsDegenerate(path[i])) {
      nulls++
      path[i] = null
    }
  }
  return nulls > 0 ? path.filter((id) => {return id !== null}) : path
}
function removeSpikesInPath(ids) {
  const n = ids.length
  if (n >= 2) {
    if (ids[0] == ~ids[n-1]) {
      ids.pop()
      ids.shift()
    } else {
      for (let i=1; i<n; i++) {
        if (ids[i-1] == ~ids[i]) {
          ids.splice(i-1, 2)
          break
        }
      }
    }
    if (ids.length < n) {
      removeSpikesInPath(ids)
    }
  }
}
export default {
  cleanShapes,
}